import React, { useEffect, useState } from 'react'
import { Button, Table, Tooltip, notification, Flex } from 'antd'
import axios from 'axios'

import {
  CheckCircleOutlined,
  CloseOutlined,
  CheckOutlined
} from '@ant-design/icons'


export default function Audit(props) {
  const [dataSource, setdataSource] = useState([])
  const { roleId, region, username } = JSON.parse(localStorage.getItem("token"))

  //1-superadmin 2-admin 3-editor
  useEffect(() => {
    axios.get(`/news?auditState=1&_expand=category`).then(res => {
      const list = res.data
      const newList = roleId === 1 ? list : [
        ...list.filter(item => item.author === username),
        ...list.filter(item => item.region === region && roleId === 3)
      ]
      setdataSource(newList)

    })
  }, [roleId, region, username])
  const handleAudit = (item, tag) => {
    var params
    if (tag === 1) {
      params = { auditState: 2, publishState: 1 }
    } else {
      params = { auditState: 3, publishState: 0 }
    }

    axios.patch(`/news/${item.id}`, params).then(res => {
      notification.info({
        message: `通知`,
        description: `您可以到【审核管理/审核列表】中查看您的新闻审核状态!`,
        placement: "bottomRight"
      })
      setdataSource(dataSource.filter(data => data.id !== item.id))
      // props.history.push(`/news-manage/update/${item.id}`)
    })

  };

  const columns = [
    // {
    //   title: 'ID',
    //   dataIndex: 'id',
    //   render: (id) => {
    //     return <b>{id}</b>
    //   }
    // },
    {
      title: '新闻标题',
      dataIndex: 'title',
      render: (title, item) => {
        return <a href={`#/news-manage/preview/${item.id}`} >{title}</a>
      }
    },
    {
      title: '作者',
      dataIndex: 'author',
    },
    {
      title: '新闻分类',
      dataIndex: 'category',
      render: (category) => {
        return category.title
      }
    },
    {
      title: '操作',
      render: (item) => {
        return <div>
          <Flex wrap="wrap" gap="small">
            <Tooltip title="通过">
              <Button onClick={() => { handleAudit(item, 1) }} type="primary" shape="circle" icon={<CheckOutlined />} />
            </Tooltip>
            <Tooltip title="驳回">
              <Button onClick={() => { handleAudit(item, 0) }} type="primary" shape="circle" icon={<CloseOutlined />} danger />
            </Tooltip>
          </Flex>
        </div>
      }
    },
  ];

  return (
    <div>
      <Table dataSource={dataSource} columns={columns}
        pagination={{
          pageSize: 5
        }}
        rowKey={(item) => item.id}
      />
    </div>
  )
}
